<?php

namespace app\api\job;

use think\facade\Log;
use think\queue\Job;
use app\model\ChargeRecord;
use pay\EncryptHelp;

/**
 * 充值订单队列
 */
class ChargeJob
{
    /**
     * 取消订单任务
     * @param Job $job 当前的任务对象
     * @param array $data 发布任务时自定义的数据
     */
    public function cancelOrder(Job $job, array $data)
    {
        // 查询订单状态
        $order = ChargeRecord::where(["id"=> $data["id"], "order_status"=>0, "pay_status"=>0])->find();
        if(!$order){
            $job->delete();
            return;
        }
        // 创建时间大于30分钟，取消订单
        if(time() - strtotime($order->create_time) > 1800){
            $state = ChargeRecord::where(["id"=> $data["id"], "order_status"=>0, "pay_status"=>0])->save(["order_status" => 3]);
            if($state){
                Log::channel("api")->write(sprintf("充值订单取消，订单号：%s", var_export($order->shop_order, true)));
                $job->delete();
                return;
            }
        }else{
            // 未到时间，删除job 且10秒后重新发布。
            $job->delete();
            $job->release(10);
        }
    }

    /**
     * 通知三方网站
     * @param Job $job
     * @param array $data
     * @return void
     */
    public function noticePartiesWeb(Job $job, array $data)
    {
        $url = $data["url"];
        unset($data["url"]);
        unset($data["id"]);
        // 通知3次
        if($job->attempts() <= 3){
            // 请求三方网站
            $result = EncryptHelp::http_post_json($url, $data);
            if($result == 'success'){
                ChargeRecord::where(["id"=> $data["id"]])->save(["notice_status" => true]);
                $job->delete();
                return;
            }
        }
    }
}